/*
To implement a doubly linked list.
Program by Thomas Jacob & Syam Kumar
26 February,2001
*/

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

typedef struct node item;
struct node
{
 int data;
 item *prev;
 item *next;
} *start=NULL;

void msg(char *s)
{
 printf("\n%s\n",s);
 getch();
}

item* find(int value)
{
 int found=0;
 item *cursor,*save;

 cursor=start;
 while(!found && cursor!=NULL)
  if(cursor->data==value) found=1;
  else cursor=cursor->next;
 if(found) return(cursor);
 else return(NULL);

}

item* add()
{
 char cont,lor;
 item *insloc,*new;
 int value,search;

 printf("Add to location <A>fter or <B>efore ? "); lor=toupper(getche());

 do
 {
  printf("\nData: ");   scanf("%d",&value);
  if(start==NULL)
   {
    start=(item *)malloc(sizeof(item));
    start->data=value;  start->next=NULL;
    start->prev=NULL;   new=start;
   }
  else
   {
    gotoxy(25,wherey()-1);
    printf("Insert near: "); scanf("%d",&search);
    insloc=find(search);
    if(insloc)
     {
      new=(item *)malloc(sizeof(struct node));
      new->data=value;
      switch(lor)
       {
	 case 'B':
	  if(insloc==start) start=new;
	  new->next=insloc; insloc->prev->next=new;
	  new->prev=insloc->prev; insloc->prev=new;
	  break;

	 default:
	  new->prev=insloc; insloc->next->prev=new;
	  new->next=insloc->next; insloc->next=new;
	  break;
       }
     }
    }
  gotoxy(50,wherey()-1);
  printf("Continue<Y/N>? ");
  cont=toupper(getche());
 } while(cont!='N');
 return(new);
}

void view()
{
 item *cursor=start;

 if(start==NULL) printf("<EMPTY>");
 else
   while(cursor!=NULL)
    {
     printf("%d\t",cursor->data);
     cursor=cursor->next;
    }
}

void delete()
{
 item* pos;
 int value;

 printf("Value to delete: ");
 scanf("%d",&value);
 pos=find(value);
 if(pos)
  {
   if(pos==start) start= pos->next;
   pos->prev->next=pos->next;
   pos->next->prev=pos->prev;
   free(pos);
  }
}

void main()
{
 char choice;
 item *curr;

 do
 {
   clrscr();
   printf("---DOUBLY LINKED LIST----\n");
   printf("Contents : ");
   view();
   printf("\n\n<I> . . . Insert\n");
   printf("<D> . . . Delete\n");
   printf("<X> . . . Exit\n\n");
   printf("Choice: ");
   choice=toupper(getche());
   printf("\n");
   switch(choice)
   {
    case 'I':curr=add();
	     break;
    case 'D':if(start==NULL) msg("List emptfy");
	     else delete();
	     break;
    case 'V':if(start==NULL) msg("List empty");
	     else view(curr);
	     break;
   }
 }while(choice!='X');
}

